import { Component, inject } from '@angular/core';
import { NonNullableFormBuilder, Validators } from '@angular/forms';
import { Router } from '@angular/router';
import { AuthService } from '../services/auth.service';
import { MessageService } from '../services/message.service';
import { LoginRequest } from '../models/auth.model';

@Component({
  selector: 'app-login',
  standalone: false,
  templateUrl: './login.component.html',
  styleUrl: './login.component.less',
})
export class LoginComponent {
  private fb = inject(NonNullableFormBuilder);
  private authService = inject(AuthService);
  private router = inject(Router);
  private messageService = inject(MessageService);

  // 创建响应式表单
  loginForm = this.fb.group({
    email: ['', [Validators.required, Validators.email]],
    password: ['', [Validators.required, Validators.minLength(6)]],
    remember: [false]
  });

  // 加载状态
  loading = false;

  // 提交表单
  onSubmit(): void {
    if (this.loginForm.valid) {
      this.loading = true;
      const formValue = this.loginForm.value;

      const loginData: LoginRequest = {
        email: formValue.email!,
        password: formValue.password!
      };

      this.authService.login(loginData).subscribe({
        next: (response) => {
          console.log('login success', response);
          this.loading = false;
          
          // 显示成功消息
          this.messageService.success('登录成功！');

          // 登录成功后跳转到首页（或用户想要访问的页面）
          this.router.navigate(['/admin']);
        },
        error: () => {
          this.loading = false;
          // 错误消息由拦截器自动处理，这里只需要重置状态
        }
      });
    } else {
      // 标记所有字段为已触碰，以显示验证错误
      Object.values(this.loginForm.controls).forEach(control => {
        control.markAsTouched();
      });
    }
  }

  // 跳转到注册页面
  goToRegister(): void {
    this.router.navigate(['/register']);
  }

  // 获取表单控件的验证状态
  getFieldError(fieldName: string): string {
    const field = this.loginForm.get(fieldName);
    if (field && field.errors && field.touched) {
      if (field.errors['required']) {
        const fieldNames: { [key: string]: string } = {
          'email': '邮箱',
          'password': '密码'
        };
        return `${fieldNames[fieldName]}不能为空`;
      }
      if (field.errors['email']) {
        return '请输入有效的邮箱地址';
      }
      if (field.errors['minlength']) {
        const requiredLength = field.errors['minlength'].requiredLength;
        return `密码至少需要${requiredLength}个字符`;
      }
    }
    return '';
  }

  // 检查字段是否有错误
  hasFieldError(fieldName: string): boolean {
    const field = this.loginForm.get(fieldName);
    return !!(field && field.errors && field.touched);
  }
}
